import os
import json
import numpy as np
# 类和索引
CLASSES=["mark","pool"]
def convert_2(size,box):
    w = (box[1] - box[0]) / size[0]
    h = (box[3] - box[2]) / size[1]
    x = (box[0]+box[1]) /2 /size[0]
    y = (box[2]+box[3]) /2 /size[1]
    return (x,y,w,h)

def json2txt(path_json,path_txt):
    with open(path_json,"r") as path_json:
        jsonx=json.load(path_json)
        width=int(jsonx["imageWidth"])      # 原图的宽
        height=int(jsonx["imageHeight"])    # 原图的高

        with open(path_txt,"w+") as ftxt:
            # 遍历每一个bbox对象
            for shape in jsonx["shapes"]:
                obj_cls=str(shape["label"])     # 获取类别
                cls_id=CLASSES.index(obj_cls)   # 获取类别索引

                points=np.array(shape["points"])    # 获取(x1,y1,x2,y2)
                #print(points)
                xmin = int(points[0][0])
                xmax = int(points[0][0])
                ymin = int(points[0][1])
                ymax = int(points[0][1])
                for point in shape["points"]:
                    if point[0] > xmax:
                        xmax = point[0]
                    if point[0] < xmin:
                        xmin = point[0]
                    if point[1] > ymax:
                        ymax = point[1]
                    if point[1] < ymin:
                        ymin = point[1]
                #print(xmin,xmax,ymin,ymax)
                # (左上角,右下角) -> (中心点,宽高) 归一化
                bb=convert_2((width,height),(xmin,xmax,ymin,ymax))

                ftxt.write(str(cls_id)+" "+" ".join([str(a) for a in bb])+"\n")#.join()
if __name__=="__main__":
    # json文件夹
    dir_json="F:\\CAM1_out\\"
    # txt文件夹
    dir_txt="F:\\txtout\\"
    if not os.path.exists(dir_txt):
        os.makedirs(dir_txt)
    # 得到所有json文件
    list_json=os.listdir(dir_json)

    # 遍历每一个json文件,转成txt文件
    for cnt, json_name in enumerate(list_json):
        #print("cnt=%d,name=%s"%(cnt, json_name))
        file,fileext = os.path.splitext(json_name)
        if(fileext == ".json"):
            path_json = dir_json + json_name
            path_txt= dir_txt + json_name.replace(".json",".txt")
            # (x1,y1,x2,y2)->(x,y,w,h)
            json2txt(path_json,path_txt)
        else:
            pass
